<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\XcUser;
use App\Models\XcUserXiche;
use App\Models\User;
use App\Models\XcDevice;
use App\Models\XcSiteOrder;
use App\Models\XcUserRecharge;

/**
 * 微信用户管理控制层
 *
 */
class XuserController extends Controller
{
	/**
	 * 获得单个用户的信息
	 * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
	 */ 
	public function info(Request $request)
	{
		$res = ['code' => -1, 'msg' => 'failed'];
		$openid = $request->get("openid");
		$xcuser = XcUserXiche::where("openid", $openid)->first();
		$res['code'] = 0;
		$res['msg']  = 'success';
		$res['data'] = $xcuser;
		return response()->json($res);
	}

	/**
	 * 更新用户的信息，主要是手机号码
	 * 
	 */ 
	public function updatemobile(Request $request)
	{
		$res = ['code' => -1, 'msg' => 'failed'];
		$openid = $request->get("openid");
		$mobile = $request->get("mobile");
		$nickname = $this->RandNickname();

		$flag = XcUser::where("openid", $openid)->update(['mobile' => $mobile, 'nickname' => $nickname, 'status' => 1]);
		if ($flag) $res = ['code' => 0, 'msg' => 'success', 'data' =>$flag];
		return response()->json($res);
	}

    /**
     * 更新用户的信息
     * @param Request $request
     * @return
     */
    public function updateInfo(Request $request)
    {
        $res = ['code' => -1, 'msg' => 'failed'];

        $openid = $request->post("openid");
        $mobile = $request->post("mobile");
        $nickname = $request->post("nickname");
        $headimgurl = $request->post("headimgurl");

        $update = [];
        if ($mobile) {
            $update['mobile'] = $mobile;
        }

        if ($nickname) {
            $update['nickname'] = $nickname;
        }

        if ($headimgurl) {
            $update['headimgurl'] = $headimgurl;
        }

        $flag = $update ? XcUser::where("openid", $openid)->update($update) : 0;
        if ($flag) $res = ['code' => 0, 'msg' => 'success', 'data' => $flag];

        return response()->json($res);
    }

	//随机生成用户昵称，前缀用DYSH
	private function RandNickname()
	{
		$nickname = substr(md5(uniqid(rand(1,6))), 0, 8);
		return 'DYSH'.$nickname;	
	}

	/**
	 * 返回用户会员卡的列表；会员卡、次卡
	 * 
	 */ 
	public function usercard(Request $request)
	{
		$res = ['code' => -1, 'msg' => 'failed'];
		$openid  = $request->get("openid");
		$swid 	 = $request->get("swid");
		$xcuser  = XcUser::where("openid", $openid)->first();
		$xuserrecharg = new XcUserRecharge();
		$list    = $xuserrecharg->GetUserRechargeArra($xcuser->id, $xcuser->openid, $swid);
		$res['code'] = 0;
		$res['msg']  = 'success';
		$res['data'] = $list;
		return response()->json($res);
	}

	/**
	 * 小程序页面关于我统计年卡和次卡数目
	 */ 
	public function aboutme(Request $request)
	{
		$res = ['code' => -1, 'msg' => 'failed'];
		$card_count_arra = ['usercard' => 0, 'cicard' => 0];
		$openid = $request->get("openid");
		$xcuser = XcUser::where("openid", $openid)->first();
		$recharge = XcUserRecharge::whereIn('type', [2,3,4,5])->where([['user_id', '=', $xcuser->id],['pay_status', '=', 2]])->orderby("created_at", 'asc')->get();

		foreach($recharge as $k => $v)
		{
			if (in_array($v->type, [2,3,4])){
				$card_count_arra['usercard'] += 1;
			}else if ($v->type == 5){
				$card_count_arra['cicard'] += 1;
			}
		}
		$res['code'] = 0;
		$res['msg']  = 'success';
		$res['data'] = ['userinfo' => $xcuser, 'cardlist' => $card_count_arra];

		return response()->json($res);

	}

	/**
	 * 获得卡的列表，分会员卡和次卡,按照购买的先后顺序排序
	 * 会员卡：type: 2,3,4
	 * 次卡  ：type: 5
	 * 
     * @param string openid 微信 openid
     * @param string typestr  usercard/cicard : 会员卡/次卡
     * @return \Illuminate\Http\JsonResponse
  	 */ 
	public function cardlist(Request $request)
	{
		$res = ['code' => -1, 'msg' => 'failed'];
		$userid = $request->get("userid");
		$typestr = $request->get("typestr", 'usercard');
		$card_arra = ['usercard' => [2,3,4], 'cicard' => [5]];
		$cardlist = XcUserRecharge::whereIn('type', $card_arra[$typestr])->where([['user_id', '=', $userid]])->orderby("created_at", 'asc')->get();
		
		$res['code'] = 0;
		$res['msg']  = 'success';
		$res['data'] =  $cardlist;
		return response()->json($res);
	}

	/**
	 * 获得用户是否有完成的订单，有则直接跳转到启动页面
	 * 
     * @param string openid 微信 openid
     * @param string open_sn 设备对外编号 
     * @return \Illuminate\Http\JsonResponse
	 */ 
	public function getorder(Request $request)
	{
		$res = ['code' => -1, 'msg' => 'failed'];
		$openid 	= $request->get("openid");
		$open_sn 	= $request->get("open_sn");
		$xcdevice      = XcDevice::where("open_sn", $open_sn)->first();
        if (empty($xcdevice)){
            $res['msg']  = 'open_sn不存在';
            return response()->json($res);
        }
        $device_no = $xcdevice->device_no;
		$siteorder 	= XcSiteOrder::where([["openid", '=', $openid],['device_no','=', $device_no],['status','=', 0],['type','=', 6]])->with("userrechage")->orderby("id", "desc")->get()->toArray();

		if (!empty($siteorder) && isset($siteorder[0]['userrechage']['pay_status']) && $siteorder[0]['userrechage']['pay_status'] == 2 && $siteorder[0]['userrechage']['status'] == 2){
			$res['code'] = 0;
			$res['msg']  = 'success';
			$res['data'] =  $siteorder[0];
		}

		return response()->json($res);
	}

	/**
	 * 小程序端用户转换，即查询用户是否是管理员
	 * 
     * @param string openid 微信 openid
	 * @return \Illuminate\Http\JsonResponse
	 */ 
	public function getuserrole(Request $request)
	{
		$res = ['code' => -1, 'msg' => 'failed'];
		$openid = $request->get("openid");
		$xcuser = Xcuser::where('openid', $openid)->first();
		if (empty($xcuser)){
			return response()->json($res);
		}
		$user = User::where('phone', $xcuser->mobile)->first();
		if (!empty($user)){
			$user->roles = $user->roles()->get()->toArray();
			$res['code'] = 0;
			$res['msg']  = 'success';
			$res['data'] =  $user;
		}
		
		return response()->json($res);
	}

}